home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2008 February / PCWFEB08.iso / Software / Freeware / Miro 1.0 / Miro_Installer.exe / Miro_Downloader.exe / urllib.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2007-11-12  |  45.8 KB  |  1,770 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.5)
  3.  
  4. '''Open an arbitrary URL.
  5.  
  6. See the following document for more info on URLs:
  7. "Names and Addresses, URIs, URLs, URNs, URCs", at
  8. http://www.w3.org/pub/WWW/Addressing/Overview.html
  9.  
  10. See also the HTTP spec (from which the error codes are derived):
  11. "HTTP - Hypertext Transfer Protocol", at
  12. http://www.w3.org/pub/WWW/Protocols/
  13.  
  14. Related standards and specs:
  15. - RFC1808: the "relative URL" spec. (authoritative status)
  16. - RFC1738 - the "URL standard". (authoritative status)
  17. - RFC1630 - the "URI spec". (informational status)
  18.  
  19. The object returned by URLopener().open(file) will differ per
  20. protocol.  All you know is that is has methods read(), readline(),
  21. readlines(), fileno(), close() and info().  The read*(), fileno()
  22. and close() methods work like those of open files.
  23. The info() method returns a mimetools.Message object which can be
  24. used to query various info about the object, if available.
  25. (mimetools.Message objects are queried with the getheader() method.)
  26. '''
  27. import string
  28. import socket
  29. import os
  30. import time
  31. import sys
  32. from urlparse import urljoin as basejoin
  33. __all__ = [
  34.     'urlopen',
  35.     'URLopener',
  36.     'FancyURLopener',
  37.     'urlretrieve',
  38.     'urlcleanup',
  39.     'quote',
  40.     'quote_plus',
  41.     'unquote',
  42.     'unquote_plus',
  43.     'urlencode',
  44.     'url2pathname',
  45.     'pathname2url',
  46.     'splittag',
  47.     'localhost',
  48.     'thishost',
  49.     'ftperrors',
  50.     'basejoin',
  51.     'unwrap',
  52.     'splittype',
  53.     'splithost',
  54.     'splituser',
  55.     'splitpasswd',
  56.     'splitport',
  57.     'splitnport',
  58.     'splitquery',
  59.     'splitattr',
  60.     'splitvalue',
  61.     'splitgophertype',
  62.     'getproxies']
  63. __version__ = '1.17'
  64. MAXFTPCACHE = 10
  65. if os.name == 'mac':
  66.     from macurl2path import url2pathname, pathname2url
  67. elif os.name == 'nt':
  68.     from nturl2path import url2pathname, pathname2url
  69. elif os.name == 'riscos':
  70.     from rourl2path import url2pathname, pathname2url
  71. else:
  72.     
  73.     def url2pathname(pathname):
  74.         """OS-specific conversion from a relative URL of the 'file' scheme
  75.         to a file system path; not recommended for general use."""
  76.         return unquote(pathname)
  77.  
  78.     
  79.     def pathname2url(pathname):
  80.         """OS-specific conversion from a file system path to a relative URL
  81.         of the 'file' scheme; not recommended for general use."""
  82.         return quote(pathname)
  83.  
  84. _urlopener = None
  85.  
  86. def urlopen(url, data = None, proxies = None):
  87.     '''urlopen(url [, data]) -> open file-like object'''
  88.     global _urlopener
  89.     if proxies is not None:
  90.         opener = FancyURLopener(proxies = proxies)
  91.     elif not _urlopener:
  92.         opener = FancyURLopener()
  93.         _urlopener = opener
  94.     else:
  95.         opener = _urlopener
  96.     if data is None:
  97.         return opener.open(url)
  98.     else:
  99.         return opener.open(url, data)
  100.  
  101.  
  102. def urlretrieve(url, filename = None, reporthook = None, data = None):
  103.     global _urlopener
  104.     if not _urlopener:
  105.         _urlopener = FancyURLopener()
  106.     
  107.     return _urlopener.retrieve(url, filename, reporthook, data)
  108.  
  109.  
  110. def urlcleanup():
  111.     if _urlopener:
  112.         _urlopener.cleanup()
  113.     
  114.  
  115.  
  116. class ContentTooShortError(IOError):
  117.     
  118.     def __init__(self, message, content):
  119.         IOError.__init__(self, message)
  120.         self.content = content
  121.  
  122.  
  123. ftpcache = { }
  124.  
  125. class URLopener:
  126.     """Class to open URLs.
  127.     This is a class rather than just a subroutine because we may need
  128.     more than one set of global protocol-specific options.
  129.     Note -- this is a base class for those who don't want the
  130.     automatic handling of errors type 302 (relocated) and 401
  131.     (authorization needed)."""
  132.     __tempfiles = None
  133.     version = 'Python-urllib/%s' % __version__
  134.     
  135.     def __init__(self, proxies = None, **x509):
  136.         if proxies is None:
  137.             proxies = getproxies()
  138.         
  139.         if not hasattr(proxies, 'has_key'):
  140.             raise AssertionError, 'proxies must be a mapping'
  141.         self.proxies = proxies
  142.         self.key_file = x509.get('key_file')
  143.         self.cert_file = x509.get('cert_file')
  144.         self.addheaders = [
  145.             ('User-Agent', self.version)]
  146.         self._URLopener__tempfiles = []
  147.         self._URLopener__unlink = os.unlink
  148.         self.tempcache = None
  149.         self.ftpcache = ftpcache
  150.  
  151.     
  152.     def __del__(self):
  153.         self.close()
  154.  
  155.     
  156.     def close(self):
  157.         self.cleanup()
  158.  
  159.     
  160.     def cleanup(self):
  161.         if self._URLopener__tempfiles:
  162.             for file in self._URLopener__tempfiles:
  163.                 
  164.                 try:
  165.                     self._URLopener__unlink(file)
  166.                 continue
  167.                 except OSError:
  168.                     continue
  169.                 
  170.  
  171.             
  172.             del self._URLopener__tempfiles[:]
  173.         
  174.         if self.tempcache:
  175.             self.tempcache.clear()
  176.         
  177.  
  178.     
  179.     def addheader(self, *args):
  180.         """Add a header to be used by the HTTP interface only
  181.         e.g. u.addheader('Accept', 'sound/basic')"""
  182.         self.addheaders.append(args)
  183.  
  184.     
  185.     def open(self, fullurl, data = None):
  186.         """Use URLopener().open(file) instead of open(file, 'r')."""
  187.         fullurl = unwrap(toBytes(fullurl))
  188.         if self.tempcache and fullurl in self.tempcache:
  189.             (filename, headers) = self.tempcache[fullurl]
  190.             fp = open(filename, 'rb')
  191.             return addinfourl(fp, headers, fullurl)
  192.         
  193.         (urltype, url) = splittype(fullurl)
  194.         if not urltype:
  195.             urltype = 'file'
  196.         
  197.         if urltype in self.proxies:
  198.             proxy = self.proxies[urltype]
  199.             (urltype, proxyhost) = splittype(proxy)
  200.             (host, selector) = splithost(proxyhost)
  201.             url = (host, fullurl)
  202.         else:
  203.             proxy = None
  204.         name = 'open_' + urltype
  205.         self.type = urltype
  206.         name = name.replace('-', '_')
  207.         if not hasattr(self, name):
  208.             if proxy:
  209.                 return self.open_unknown_proxy(proxy, fullurl, data)
  210.             else:
  211.                 return self.open_unknown(fullurl, data)
  212.         
  213.         
  214.         try:
  215.             if data is None:
  216.                 return getattr(self, name)(url)
  217.             else:
  218.                 return getattr(self, name)(url, data)
  219.         except socket.error:
  220.             msg = None
  221.             raise IOError, ('socket error', msg), sys.exc_info()[2]
  222.  
  223.  
  224.     
  225.     def open_unknown(self, fullurl, data = None):
  226.         '''Overridable interface to open unknown URL type.'''
  227.         (type, url) = splittype(fullurl)
  228.         raise IOError, ('url error', 'unknown url type', type)
  229.  
  230.     
  231.     def open_unknown_proxy(self, proxy, fullurl, data = None):
  232.         '''Overridable interface to open unknown URL type.'''
  233.         (type, url) = splittype(fullurl)
  234.         raise IOError, ('url error', 'invalid proxy for %s' % type, proxy)
  235.  
  236.     
  237.     def retrieve(self, url, filename = None, reporthook = None, data = None):
  238.         '''retrieve(url) returns (filename, headers) for a local object
  239.         or (tempfilename, headers) for a remote object.'''
  240.         url = unwrap(toBytes(url))
  241.         if self.tempcache and url in self.tempcache:
  242.             return self.tempcache[url]
  243.         
  244.         (type, url1) = splittype(url)
  245.         if filename is None:
  246.             if not type or type == 'file':
  247.                 
  248.                 try:
  249.                     fp = self.open_local_file(url1)
  250.                     hdrs = fp.info()
  251.                     del fp
  252.                     return (url2pathname(splithost(url1)[1]), hdrs)
  253.                 except IOError:
  254.                     msg = None
  255.                 except:
  256.                     None<EXCEPTION MATCH>IOError
  257.                 
  258.  
  259.         None<EXCEPTION MATCH>IOError
  260.         fp = self.open(url, data)
  261.         headers = fp.info()
  262.         if filename:
  263.             tfp = open(filename, 'wb')
  264.         else:
  265.             import tempfile
  266.             (garbage, path) = splittype(url)
  267.             if not path:
  268.                 pass
  269.             (garbage, path) = splithost('')
  270.             if not path:
  271.                 pass
  272.             (path, garbage) = splitquery('')
  273.             if not path:
  274.                 pass
  275.             (path, garbage) = splitattr('')
  276.             suffix = os.path.splitext(path)[1]
  277.             (fd, filename) = tempfile.mkstemp(suffix)
  278.             self._URLopener__tempfiles.append(filename)
  279.             tfp = os.fdopen(fd, 'wb')
  280.         result = (filename, headers)
  281.         if self.tempcache is not None:
  282.             self.tempcache[url] = result
  283.         
  284.         bs = 8192
  285.         size = -1
  286.         read = 0
  287.         blocknum = 0
  288.         if reporthook:
  289.             if 'content-length' in headers:
  290.                 size = int(headers['Content-Length'])
  291.             
  292.             reporthook(blocknum, bs, size)
  293.         
  294.         while None:
  295.             block = fp.read(bs)
  296.             if block == '':
  297.                 break
  298.             
  299.             read += len(block)
  300.             blocknum += 1
  301.             if reporthook:
  302.                 reporthook(blocknum, bs, size)
  303.                 continue
  304.             continue
  305.             fp.close()
  306.             tfp.close()
  307.             del fp
  308.             del tfp
  309.             if size >= 0 and read < size:
  310.                 raise ContentTooShortError('retrieval incomplete: got only %i out of %i bytes' % (read, size), result)
  311.             
  312.         return result
  313.  
  314.     
  315.     def open_http(self, url, data = None):
  316.         '''Use HTTP protocol.'''
  317.         import httplib
  318.         user_passwd = None
  319.         proxy_passwd = None
  320.         if isinstance(url, str):
  321.             (host, selector) = splithost(url)
  322.             if host:
  323.                 (user_passwd, host) = splituser(host)
  324.                 host = unquote(host)
  325.             
  326.             realhost = host
  327.         else:
  328.             (host, selector) = url
  329.             (proxy_passwd, host) = splituser(host)
  330.             (urltype, rest) = splittype(selector)
  331.             url = rest
  332.             user_passwd = None
  333.             if urltype.lower() != 'http':
  334.                 realhost = None
  335.             else:
  336.                 (realhost, rest) = splithost(rest)
  337.                 if realhost:
  338.                     (user_passwd, realhost) = splituser(realhost)
  339.                 
  340.                 if user_passwd:
  341.                     selector = '%s://%s%s' % (urltype, realhost, rest)
  342.                 
  343.                 if proxy_bypass(realhost):
  344.                     host = realhost
  345.                 
  346.         if not host:
  347.             raise IOError, ('http error', 'no host given')
  348.         
  349.         if proxy_passwd:
  350.             import base64
  351.             proxy_auth = base64.encodestring(proxy_passwd).strip()
  352.         else:
  353.             proxy_auth = None
  354.         if user_passwd:
  355.             import base64
  356.             auth = base64.encodestring(user_passwd).strip()
  357.         else:
  358.             auth = None
  359.         h = httplib.HTTP(host)
  360.         if data is not None:
  361.             h.putrequest('POST', selector)
  362.             h.putheader('Content-Type', 'application/x-www-form-urlencoded')
  363.             h.putheader('Content-Length', '%d' % len(data))
  364.         else:
  365.             h.putrequest('GET', selector)
  366.         if proxy_auth:
  367.             h.putheader('Proxy-Authorization', 'Basic %s' % proxy_auth)
  368.         
  369.         if auth:
  370.             h.putheader('Authorization', 'Basic %s' % auth)
  371.         
  372.         if realhost:
  373.             h.putheader('Host', realhost)
  374.         
  375.         for args in self.addheaders:
  376.             h.putheader(*args)
  377.         
  378.         h.endheaders()
  379.         if data is not None:
  380.             h.send(data)
  381.         
  382.         (errcode, errmsg, headers) = h.getreply()
  383.         fp = h.getfile()
  384.         if errcode == 200:
  385.             return addinfourl(fp, headers, 'http:' + url)
  386.         elif data is None:
  387.             return self.http_error(url, fp, errcode, errmsg, headers)
  388.         else:
  389.             return self.http_error(url, fp, errcode, errmsg, headers, data)
  390.  
  391.     
  392.     def http_error(self, url, fp, errcode, errmsg, headers, data = None):
  393.         '''Handle http errors.
  394.         Derived class can override this, or provide specific handlers
  395.         named http_error_DDD where DDD is the 3-digit error code.'''
  396.         name = 'http_error_%d' % errcode
  397.         if hasattr(self, name):
  398.             method = getattr(self, name)
  399.             if data is None:
  400.                 result = method(url, fp, errcode, errmsg, headers)
  401.             else:
  402.                 result = method(url, fp, errcode, errmsg, headers, data)
  403.             if result:
  404.                 return result
  405.             
  406.         
  407.         return self.http_error_default(url, fp, errcode, errmsg, headers)
  408.  
  409.     
  410.     def http_error_default(self, url, fp, errcode, errmsg, headers):
  411.         '''Default error handler: close the connection and raise IOError.'''
  412.         void = fp.read()
  413.         fp.close()
  414.         raise IOError, ('http error', errcode, errmsg, headers)
  415.  
  416.     if hasattr(socket, 'ssl'):
  417.         
  418.         def open_https(self, url, data = None):
  419.             '''Use HTTPS protocol.'''
  420.             import httplib
  421.             user_passwd = None
  422.             proxy_passwd = None
  423.             if isinstance(url, str):
  424.                 (host, selector) = splithost(url)
  425.                 if host:
  426.                     (user_passwd, host) = splituser(host)
  427.                     host = unquote(host)
  428.                 
  429.                 realhost = host
  430.             else:
  431.                 (host, selector) = url
  432.                 (proxy_passwd, host) = splituser(host)
  433.                 (urltype, rest) = splittype(selector)
  434.                 url = rest
  435.                 user_passwd = None
  436.                 if urltype.lower() != 'https':
  437.                     realhost = None
  438.                 else:
  439.                     (realhost, rest) = splithost(rest)
  440.                     if realhost:
  441.                         (user_passwd, realhost) = splituser(realhost)
  442.                     
  443.                     if user_passwd:
  444.                         selector = '%s://%s%s' % (urltype, realhost, rest)
  445.                     
  446.             if not host:
  447.                 raise IOError, ('https error', 'no host given')
  448.             
  449.             if proxy_passwd:
  450.                 import base64
  451.                 proxy_auth = base64.encodestring(proxy_passwd).strip()
  452.             else:
  453.                 proxy_auth = None
  454.             if user_passwd:
  455.                 import base64
  456.                 auth = base64.encodestring(user_passwd).strip()
  457.             else:
  458.                 auth = None
  459.             h = httplib.HTTPS(host, 0, key_file = self.key_file, cert_file = self.cert_file)
  460.             if data is not None:
  461.                 h.putrequest('POST', selector)
  462.                 h.putheader('Content-Type', 'application/x-www-form-urlencoded')
  463.                 h.putheader('Content-Length', '%d' % len(data))
  464.             else:
  465.                 h.putrequest('GET', selector)
  466.             if proxy_auth:
  467.                 h.putheader('Proxy-Authorization: Basic %s' % proxy_auth)
  468.             
  469.             if auth:
  470.                 h.putheader('Authorization: Basic %s' % auth)
  471.             
  472.             if realhost:
  473.                 h.putheader('Host', realhost)
  474.             
  475.             for args in self.addheaders:
  476.                 h.putheader(*args)
  477.             
  478.             h.endheaders()
  479.             if data is not None:
  480.                 h.send(data)
  481.             
  482.             (errcode, errmsg, headers) = h.getreply()
  483.             fp = h.getfile()
  484.             if errcode == 200:
  485.                 return addinfourl(fp, headers, 'https:' + url)
  486.             elif data is None:
  487.                 return self.http_error(url, fp, errcode, errmsg, headers)
  488.             else:
  489.                 return self.http_error(url, fp, errcode, errmsg, headers, data)
  490.  
  491.     
  492.     
  493.     def open_gopher(self, url):
  494.         '''Use Gopher protocol.'''
  495.         if not isinstance(url, str):
  496.             raise IOError, ('gopher error', 'proxy support for gopher protocol currently not implemented')
  497.         
  498.         import gopherlib
  499.         (host, selector) = splithost(url)
  500.         if not host:
  501.             raise IOError, ('gopher error', 'no host given')
  502.         
  503.         host = unquote(host)
  504.         (type, selector) = splitgophertype(selector)
  505.         (selector, query) = splitquery(selector)
  506.         selector = unquote(selector)
  507.         if query:
  508.             query = unquote(query)
  509.             fp = gopherlib.send_query(selector, query, host)
  510.         else:
  511.             fp = gopherlib.send_selector(selector, host)
  512.         return addinfourl(fp, noheaders(), 'gopher:' + url)
  513.  
  514.     
  515.     def open_file(self, url):
  516.         '''Use local file or FTP depending on form of URL.'''
  517.         if not isinstance(url, str):
  518.             raise IOError, ('file error', 'proxy support for file protocol currently not implemented')
  519.         
  520.         if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
  521.             return self.open_ftp(url)
  522.         else:
  523.             return self.open_local_file(url)
  524.  
  525.     
  526.     def open_local_file(self, url):
  527.         '''Use local file.'''
  528.         import mimetypes
  529.         import mimetools
  530.         import email.Utils as email
  531.         
  532.         try:
  533.             StringIO = StringIO
  534.             import cStringIO
  535.         except ImportError:
  536.             StringIO = StringIO
  537.             import StringIO
  538.  
  539.         (host, file) = splithost(url)
  540.         localname = url2pathname(file)
  541.         
  542.         try:
  543.             stats = os.stat(localname)
  544.         except OSError:
  545.             e = None
  546.             raise IOError(e.errno, e.strerror, e.filename)
  547.  
  548.         size = stats.st_size
  549.         modified = email.Utils.formatdate(stats.st_mtime, usegmt = True)
  550.         mtype = mimetypes.guess_type(url)[0]
  551.         if not mtype:
  552.             pass
  553.         headers = mimetools.Message(StringIO('Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' % ('text/plain', size, modified)))
  554.         if not host:
  555.             urlfile = file
  556.             if file[:1] == '/':
  557.                 urlfile = 'file://' + file
  558.             
  559.             return addinfourl(open(localname, 'rb'), headers, urlfile)
  560.         
  561.         (host, port) = splitport(host)
  562.         if not port and socket.gethostbyname(host) in (localhost(), thishost()):
  563.             urlfile = file
  564.             if file[:1] == '/':
  565.                 urlfile = 'file://' + file
  566.             
  567.             return addinfourl(open(localname, 'rb'), headers, urlfile)
  568.         
  569.         raise IOError, ('local file error', 'not on local host')
  570.  
  571.     
  572.     def open_ftp(self, url):
  573.         '''Use FTP protocol.'''
  574.         if not isinstance(url, str):
  575.             raise IOError, ('ftp error', 'proxy support for ftp protocol currently not implemented')
  576.         
  577.         import mimetypes
  578.         import mimetools
  579.         
  580.         try:
  581.             StringIO = StringIO
  582.             import cStringIO
  583.         except ImportError:
  584.             StringIO = StringIO
  585.             import StringIO
  586.  
  587.         (host, path) = splithost(url)
  588.         if not host:
  589.             raise IOError, ('ftp error', 'no host given')
  590.         
  591.         (host, port) = splitport(host)
  592.         (user, host) = splituser(host)
  593.         if user:
  594.             (user, passwd) = splitpasswd(user)
  595.         else:
  596.             passwd = None
  597.         host = unquote(host)
  598.         if not user:
  599.             pass
  600.         user = unquote('')
  601.         if not passwd:
  602.             pass
  603.         passwd = unquote('')
  604.         host = socket.gethostbyname(host)
  605.         if not port:
  606.             import ftplib
  607.             port = ftplib.FTP_PORT
  608.         else:
  609.             port = int(port)
  610.         (path, attrs) = splitattr(path)
  611.         path = unquote(path)
  612.         dirs = path.split('/')
  613.         dirs = dirs[:-1]
  614.         file = dirs[-1]
  615.         if dirs and not dirs[0]:
  616.             dirs = dirs[1:]
  617.         
  618.         if dirs and not dirs[0]:
  619.             dirs[0] = '/'
  620.         
  621.         key = (user, host, port, '/'.join(dirs))
  622.         if len(self.ftpcache) > MAXFTPCACHE:
  623.             for k in self.ftpcache.keys():
  624.                 if k != key:
  625.                     v = self.ftpcache[k]
  626.                     del self.ftpcache[k]
  627.                     v.close()
  628.                     continue
  629.             
  630.         
  631.         
  632.         try:
  633.             if key not in self.ftpcache:
  634.                 self.ftpcache[key] = ftpwrapper(user, passwd, host, port, dirs)
  635.             
  636.             if not file:
  637.                 type = 'D'
  638.             else:
  639.                 type = 'I'
  640.             for attr in attrs:
  641.                 (attr, value) = splitvalue(attr)
  642.                 if attr.lower() == 'type' and value in ('a', 'A', 'i', 'I', 'd', 'D'):
  643.                     type = value.upper()
  644.                     continue
  645.             
  646.             (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
  647.             mtype = mimetypes.guess_type('ftp:' + url)[0]
  648.             headers = ''
  649.             if mtype:
  650.                 headers += 'Content-Type: %s\n' % mtype
  651.             
  652.             if retrlen is not None and retrlen >= 0:
  653.                 headers += 'Content-Length: %d\n' % retrlen
  654.             
  655.             headers = mimetools.Message(StringIO(headers))
  656.             return addinfourl(fp, headers, 'ftp:' + url)
  657.         except ftperrors():
  658.             msg = None
  659.             raise IOError, ('ftp error', msg), sys.exc_info()[2]
  660.  
  661.  
  662.     
  663.     def open_data(self, url, data = None):
  664.         '''Use "data" URL.'''
  665.         if not isinstance(url, str):
  666.             raise IOError, ('data error', 'proxy support for data protocol currently not implemented')
  667.         
  668.         import mimetools
  669.         
  670.         try:
  671.             StringIO = StringIO
  672.             import cStringIO
  673.         except ImportError:
  674.             StringIO = StringIO
  675.             import StringIO
  676.  
  677.         
  678.         try:
  679.             (type, data) = url.split(',', 1)
  680.         except ValueError:
  681.             raise IOError, ('data error', 'bad data URL')
  682.  
  683.         if not type:
  684.             type = 'text/plain;charset=US-ASCII'
  685.         
  686.         semi = type.rfind(';')
  687.         if semi >= 0 and '=' not in type[semi:]:
  688.             encoding = type[semi + 1:]
  689.             type = type[:semi]
  690.         else:
  691.             encoding = ''
  692.         msg = []
  693.         msg.append('Date: %s' % time.strftime('%a, %d %b %Y %T GMT', time.gmtime(time.time())))
  694.         msg.append('Content-type: %s' % type)
  695.         if encoding == 'base64':
  696.             import base64
  697.             data = base64.decodestring(data)
  698.         else:
  699.             data = unquote(data)
  700.         msg.append('Content-Length: %d' % len(data))
  701.         msg.append('')
  702.         msg.append(data)
  703.         msg = '\n'.join(msg)
  704.         f = StringIO(msg)
  705.         headers = mimetools.Message(f, 0)
  706.         return addinfourl(f, headers, url)
  707.  
  708.  
  709.  
  710. class FancyURLopener(URLopener):
  711.     '''Derived class with handlers for errors we can handle (perhaps).'''
  712.     
  713.     def __init__(self, *args, **kwargs):
  714.         URLopener.__init__(self, *args, **kwargs)
  715.         self.auth_cache = { }
  716.         self.tries = 0
  717.         self.maxtries = 10
  718.  
  719.     
  720.     def http_error_default(self, url, fp, errcode, errmsg, headers):
  721.         """Default error handling -- don't raise an exception."""
  722.         return addinfourl(fp, headers, 'http:' + url)
  723.  
  724.     
  725.     def http_error_302(self, url, fp, errcode, errmsg, headers, data = None):
  726.         '''Error 302 -- relocated (temporarily).'''
  727.         self.tries += 1
  728.         result = self.redirect_internal(url, fp, errcode, errmsg, headers, data)
  729.         self.tries = 0
  730.         return result
  731.  
  732.     
  733.     def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
  734.         if 'location' in headers:
  735.             newurl = headers['location']
  736.         elif 'uri' in headers:
  737.             newurl = headers['uri']
  738.         else:
  739.             return None
  740.         void = fp.read()
  741.         fp.close()
  742.         newurl = basejoin(self.type + ':' + url, newurl)
  743.         return self.open(newurl)
  744.  
  745.     
  746.     def http_error_301(self, url, fp, errcode, errmsg, headers, data = None):
  747.         '''Error 301 -- also relocated (permanently).'''
  748.         return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  749.  
  750.     
  751.     def http_error_303(self, url, fp, errcode, errmsg, headers, data = None):
  752.         '''Error 303 -- also relocated (essentially identical to 302).'''
  753.         return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  754.  
  755.     
  756.     def http_error_307(self, url, fp, errcode, errmsg, headers, data = None):
  757.         '''Error 307 -- relocated, but turn POST into error.'''
  758.         if data is None:
  759.             return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  760.         else:
  761.             return self.http_error_default(url, fp, errcode, errmsg, headers)
  762.  
  763.     
  764.     def http_error_401(self, url, fp, errcode, errmsg, headers, data = None):
  765.         '''Error 401 -- authentication required.
  766.         This function supports Basic authentication only.'''
  767.         if 'www-authenticate' not in headers:
  768.             URLopener.http_error_default(self, url, fp, errcode, errmsg, headers)
  769.         
  770.         stuff = headers['www-authenticate']
  771.         import re
  772.         match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
  773.         if not match:
  774.             URLopener.http_error_default(self, url, fp, errcode, errmsg, headers)
  775.         
  776.         (scheme, realm) = match.groups()
  777.         if scheme.lower() != 'basic':
  778.             URLopener.http_error_default(self, url, fp, errcode, errmsg, headers)
  779.         
  780.         name = 'retry_' + self.type + '_basic_auth'
  781.         if data is None:
  782.             return getattr(self, name)(url, realm)
  783.         else:
  784.             return getattr(self, name)(url, realm, data)
  785.  
  786.     
  787.     def http_error_407(self, url, fp, errcode, errmsg, headers, data = None):
  788.         '''Error 407 -- proxy authentication required.
  789.         This function supports Basic authentication only.'''
  790.         if 'proxy-authenticate' not in headers:
  791.             URLopener.http_error_default(self, url, fp, errcode, errmsg, headers)
  792.         
  793.         stuff = headers['proxy-authenticate']
  794.         import re
  795.         match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
  796.         if not match:
  797.             URLopener.http_error_default(self, url, fp, errcode, errmsg, headers)
  798.         
  799.         (scheme, realm) = match.groups()
  800.         if scheme.lower() != 'basic':
  801.             URLopener.http_error_default(self, url, fp, errcode, errmsg, headers)
  802.         
  803.         name = 'retry_proxy_' + self.type + '_basic_auth'
  804.         if data is None:
  805.             return getattr(self, name)(url, realm)
  806.         else:
  807.             return getattr(self, name)(url, realm, data)
  808.  
  809.     
  810.     def retry_proxy_http_basic_auth(self, url, realm, data = None):
  811.         (host, selector) = splithost(url)
  812.         newurl = 'http://' + host + selector
  813.         proxy = self.proxies['http']
  814.         (urltype, proxyhost) = splittype(proxy)
  815.         (proxyhost, proxyselector) = splithost(proxyhost)
  816.         i = proxyhost.find('@') + 1
  817.         proxyhost = proxyhost[i:]
  818.         (user, passwd) = self.get_user_passwd(proxyhost, realm, i)
  819.         if not user or passwd:
  820.             return None
  821.         
  822.         proxyhost = quote(user, safe = '') + ':' + quote(passwd, safe = '') + '@' + proxyhost
  823.         self.proxies['http'] = 'http://' + proxyhost + proxyselector
  824.         if data is None:
  825.             return self.open(newurl)
  826.         else:
  827.             return self.open(newurl, data)
  828.  
  829.     
  830.     def retry_proxy_https_basic_auth(self, url, realm, data = None):
  831.         (host, selector) = splithost(url)
  832.         newurl = 'https://' + host + selector
  833.         proxy = self.proxies['https']
  834.         (urltype, proxyhost) = splittype(proxy)
  835.         (proxyhost, proxyselector) = splithost(proxyhost)
  836.         i = proxyhost.find('@') + 1
  837.         proxyhost = proxyhost[i:]
  838.         (user, passwd) = self.get_user_passwd(proxyhost, realm, i)
  839.         if not user or passwd:
  840.             return None
  841.         
  842.         proxyhost = quote(user, safe = '') + ':' + quote(passwd, safe = '') + '@' + proxyhost
  843.         self.proxies['https'] = 'https://' + proxyhost + proxyselector
  844.         if data is None:
  845.             return self.open(newurl)
  846.         else:
  847.             return self.open(newurl, data)
  848.  
  849.     
  850.     def retry_http_basic_auth(self, url, realm, data = None):
  851.         (host, selector) = splithost(url)
  852.         i = host.find('@') + 1
  853.         host = host[i:]
  854.         (user, passwd) = self.get_user_passwd(host, realm, i)
  855.         if not user or passwd:
  856.             return None
  857.         
  858.         host = quote(user, safe = '') + ':' + quote(passwd, safe = '') + '@' + host
  859.         newurl = 'http://' + host + selector
  860.         if data is None:
  861.             return self.open(newurl)
  862.         else:
  863.             return self.open(newurl, data)
  864.  
  865.     
  866.     def retry_https_basic_auth(self, url, realm, data = None):
  867.         (host, selector) = splithost(url)
  868.         i = host.find('@') + 1
  869.         host = host[i:]
  870.         (user, passwd) = self.get_user_passwd(host, realm, i)
  871.         if not user or passwd:
  872.             return None
  873.         
  874.         host = quote(user, safe = '') + ':' + quote(passwd, safe = '') + '@' + host
  875.         newurl = 'https://' + host + selector
  876.         if data is None:
  877.             return self.open(newurl)
  878.         else:
  879.             return self.open(newurl, data)
  880.  
  881.     
  882.     def get_user_passwd(self, host, realm, clear_cache = 0):
  883.         key = realm + '@' + host.lower()
  884.         if key in self.auth_cache:
  885.             if clear_cache:
  886.                 del self.auth_cache[key]
  887.             else:
  888.                 return self.auth_cache[key]
  889.         
  890.         (user, passwd) = self.prompt_user_passwd(host, realm)
  891.         if user or passwd:
  892.             self.auth_cache[key] = (user, passwd)
  893.         
  894.         return (user, passwd)
  895.  
  896.     
  897.     def prompt_user_passwd(self, host, realm):
  898.         '''Override this in a GUI environment!'''
  899.         import getpass
  900.         
  901.         try:
  902.             user = raw_input('Enter username for %s at %s: ' % (realm, host))
  903.             passwd = getpass.getpass('Enter password for %s in %s at %s: ' % (user, realm, host))
  904.             return (user, passwd)
  905.         except KeyboardInterrupt:
  906.             print 
  907.             return (None, None)
  908.  
  909.  
  910.  
  911. _localhost = None
  912.  
  913. def localhost():
  914.     """Return the IP address of the magic hostname 'localhost'."""
  915.     global _localhost
  916.     if _localhost is None:
  917.         _localhost = socket.gethostbyname('localhost')
  918.     
  919.     return _localhost
  920.  
  921. _thishost = None
  922.  
  923. def thishost():
  924.     '''Return the IP address of the current host.'''
  925.     global _thishost
  926.     if _thishost is None:
  927.         _thishost = socket.gethostbyname(socket.gethostname())
  928.     
  929.     return _thishost
  930.  
  931. _ftperrors = None
  932.  
  933. def ftperrors():
  934.     '''Return the set of errors raised by the FTP class.'''
  935.     global _ftperrors
  936.     if _ftperrors is None:
  937.         import ftplib
  938.         _ftperrors = ftplib.all_errors
  939.     
  940.     return _ftperrors
  941.  
  942. _noheaders = None
  943.  
  944. def noheaders():
  945.     '''Return an empty mimetools.Message object.'''
  946.     global _noheaders
  947.     if _noheaders is None:
  948.         import mimetools
  949.         
  950.         try:
  951.             StringIO = StringIO
  952.             import cStringIO
  953.         except ImportError:
  954.             StringIO = StringIO
  955.             import StringIO
  956.  
  957.         _noheaders = mimetools.Message(StringIO(), 0)
  958.         _noheaders.fp.close()
  959.     
  960.     return _noheaders
  961.  
  962.  
  963. class ftpwrapper:
  964.     '''Class used by open_ftp() for cache of open FTP connections.'''
  965.     
  966.     def __init__(self, user, passwd, host, port, dirs):
  967.         self.user = user
  968.         self.passwd = passwd
  969.         self.host = host
  970.         self.port = port
  971.         self.dirs = dirs
  972.         self.init()
  973.  
  974.     
  975.     def init(self):
  976.         import ftplib
  977.         self.busy = 0
  978.         self.ftp = ftplib.FTP()
  979.         self.ftp.connect(self.host, self.port)
  980.         self.ftp.login(self.user, self.passwd)
  981.         for dir in self.dirs:
  982.             self.ftp.cwd(dir)
  983.         
  984.  
  985.     
  986.     def retrfile(self, file, type):
  987.         import ftplib
  988.         self.endtransfer()
  989.         if type in ('d', 'D'):
  990.             cmd = 'TYPE A'
  991.             isdir = 1
  992.         else:
  993.             cmd = 'TYPE ' + type
  994.             isdir = 0
  995.         
  996.         try:
  997.             self.ftp.voidcmd(cmd)
  998.         except ftplib.all_errors:
  999.             self.init()
  1000.             self.ftp.voidcmd(cmd)
  1001.  
  1002.         conn = None
  1003.         if file and not isdir:
  1004.             
  1005.             try:
  1006.                 cmd = 'RETR ' + file
  1007.                 conn = self.ftp.ntransfercmd(cmd)
  1008.             except ftplib.error_perm:
  1009.                 reason = None
  1010.                 if str(reason)[:3] != '550':
  1011.                     raise IOError, ('ftp error', reason), sys.exc_info()[2]
  1012.                 
  1013.             except:
  1014.                 str(reason)[:3] != '550'
  1015.             
  1016.  
  1017.         None<EXCEPTION MATCH>ftplib.error_perm
  1018.         if not conn:
  1019.             self.ftp.voidcmd('TYPE A')
  1020.             if file:
  1021.                 cmd = 'LIST ' + file
  1022.             else:
  1023.                 cmd = 'LIST'
  1024.             conn = self.ftp.ntransfercmd(cmd)
  1025.         
  1026.         self.busy = 1
  1027.         return (addclosehook(conn[0].makefile('rb'), self.endtransfer), conn[1])
  1028.  
  1029.     
  1030.     def endtransfer(self):
  1031.         if not self.busy:
  1032.             return None
  1033.         
  1034.         self.busy = 0
  1035.         
  1036.         try:
  1037.             self.ftp.voidresp()
  1038.         except ftperrors():
  1039.             pass
  1040.  
  1041.  
  1042.     
  1043.     def close(self):
  1044.         self.endtransfer()
  1045.         
  1046.         try:
  1047.             self.ftp.close()
  1048.         except ftperrors():
  1049.             pass
  1050.  
  1051.  
  1052.  
  1053.  
  1054. class addbase:
  1055.     '''Base class for addinfo and addclosehook.'''
  1056.     
  1057.     def __init__(self, fp):
  1058.         self.fp = fp
  1059.         self.read = self.fp.read
  1060.         self.readline = self.fp.readline
  1061.         if hasattr(self.fp, 'readlines'):
  1062.             self.readlines = self.fp.readlines
  1063.         
  1064.         if hasattr(self.fp, 'fileno'):
  1065.             self.fileno = self.fp.fileno
  1066.         else:
  1067.             
  1068.             self.fileno = lambda : None
  1069.         if hasattr(self.fp, '__iter__'):
  1070.             self.__iter__ = self.fp.__iter__
  1071.             if hasattr(self.fp, 'next'):
  1072.                 self.next = self.fp.next
  1073.             
  1074.         
  1075.  
  1076.     
  1077.     def __repr__(self):
  1078.         return '<%s at %r whose fp = %r>' % (self.__class__.__name__, id(self), self.fp)
  1079.  
  1080.     
  1081.     def close(self):
  1082.         self.read = None
  1083.         self.readline = None
  1084.         self.readlines = None
  1085.         self.fileno = None
  1086.         if self.fp:
  1087.             self.fp.close()
  1088.         
  1089.         self.fp = None
  1090.  
  1091.  
  1092.  
  1093. class addclosehook(addbase):
  1094.     '''Class to add a close hook to an open file.'''
  1095.     
  1096.     def __init__(self, fp, closehook, *hookargs):
  1097.         addbase.__init__(self, fp)
  1098.         self.closehook = closehook
  1099.         self.hookargs = hookargs
  1100.  
  1101.     
  1102.     def close(self):
  1103.         addbase.close(self)
  1104.         if self.closehook:
  1105.             self.closehook(*self.hookargs)
  1106.             self.closehook = None
  1107.             self.hookargs = None
  1108.         
  1109.  
  1110.  
  1111.  
  1112. class addinfo(addbase):
  1113.     '''class to add an info() method to an open file.'''
  1114.     
  1115.     def __init__(self, fp, headers):
  1116.         addbase.__init__(self, fp)
  1117.         self.headers = headers
  1118.  
  1119.     
  1120.     def info(self):
  1121.         return self.headers
  1122.  
  1123.  
  1124.  
  1125. class addinfourl(addbase):
  1126.     '''class to add info() and geturl() methods to an open file.'''
  1127.     
  1128.     def __init__(self, fp, headers, url):
  1129.         addbase.__init__(self, fp)
  1130.         self.headers = headers
  1131.         self.url = url
  1132.  
  1133.     
  1134.     def info(self):
  1135.         return self.headers
  1136.  
  1137.     
  1138.     def geturl(self):
  1139.         return self.url
  1140.  
  1141.  
  1142.  
  1143. try:
  1144.     unicode
  1145. except NameError:
  1146.     
  1147.     def _is_unicode(x):
  1148.         return 0
  1149.  
  1150.  
  1151.  
  1152. def _is_unicode(x):
  1153.     return isinstance(x, unicode)
  1154.  
  1155.  
  1156. def toBytes(url):
  1157.     '''toBytes(u"URL") --> \'URL\'.'''
  1158.     if _is_unicode(url):
  1159.         
  1160.         try:
  1161.             url = url.encode('ASCII')
  1162.         except UnicodeError:
  1163.             raise UnicodeError('URL ' + repr(url) + ' contains non-ASCII characters')
  1164.         except:
  1165.             None<EXCEPTION MATCH>UnicodeError
  1166.         
  1167.  
  1168.     None<EXCEPTION MATCH>UnicodeError
  1169.     return url
  1170.  
  1171.  
  1172. def unwrap(url):
  1173.     """unwrap('<URL:type://host/path>') --> 'type://host/path'."""
  1174.     url = url.strip()
  1175.     if url[:1] == '<' and url[-1:] == '>':
  1176.         url = url[1:-1].strip()
  1177.     
  1178.     if url[:4] == 'URL:':
  1179.         url = url[4:].strip()
  1180.     
  1181.     return url
  1182.  
  1183. _typeprog = None
  1184.  
  1185. def splittype(url):
  1186.     """splittype('type:opaquestring') --> 'type', 'opaquestring'."""
  1187.     global _typeprog
  1188.     if _typeprog is None:
  1189.         import re
  1190.         _typeprog = re.compile('^([^/:]+):')
  1191.     
  1192.     match = _typeprog.match(url)
  1193.     if match:
  1194.         scheme = match.group(1)
  1195.         return (scheme.lower(), url[len(scheme) + 1:])
  1196.     
  1197.     return (None, url)
  1198.  
  1199. _hostprog = None
  1200.  
  1201. def splithost(url):
  1202.     """splithost('//host[:port]/path') --> 'host[:port]', '/path'."""
  1203.     global _hostprog
  1204.     if _hostprog is None:
  1205.         import re
  1206.         _hostprog = re.compile('^//([^/?]*)(.*)$')
  1207.     
  1208.     match = _hostprog.match(url)
  1209.     if match:
  1210.         return match.group(1, 2)
  1211.     
  1212.     return (None, url)
  1213.  
  1214. _userprog = None
  1215.  
  1216. def splituser(host):
  1217.     """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
  1218.     global _userprog
  1219.     if _userprog is None:
  1220.         import re
  1221.         _userprog = re.compile('^(.*)@(.*)$')
  1222.     
  1223.     match = _userprog.match(host)
  1224.     if match:
  1225.         return map(unquote, match.group(1, 2))
  1226.     
  1227.     return (None, host)
  1228.  
  1229. _passwdprog = None
  1230.  
  1231. def splitpasswd(user):
  1232.     """splitpasswd('user:passwd') -> 'user', 'passwd'."""
  1233.     global _passwdprog
  1234.     if _passwdprog is None:
  1235.         import re
  1236.         _passwdprog = re.compile('^([^:]*):(.*)$')
  1237.     
  1238.     match = _passwdprog.match(user)
  1239.     if match:
  1240.         return match.group(1, 2)
  1241.     
  1242.     return (user, None)
  1243.  
  1244. _portprog = None
  1245.  
  1246. def splitport(host):
  1247.     """splitport('host:port') --> 'host', 'port'."""
  1248.     global _portprog
  1249.     if _portprog is None:
  1250.         import re
  1251.         _portprog = re.compile('^(.*):([0-9]+)$')
  1252.     
  1253.     match = _portprog.match(host)
  1254.     if match:
  1255.         return match.group(1, 2)
  1256.     
  1257.     return (host, None)
  1258.  
  1259. _nportprog = None
  1260.  
  1261. def splitnport(host, defport = -1):
  1262.     """Split host and port, returning numeric port.
  1263.     Return given default port if no ':' found; defaults to -1.
  1264.     Return numerical port if a valid number are found after ':'.
  1265.     Return None if ':' but not a valid number."""
  1266.     global _nportprog
  1267.     if _nportprog is None:
  1268.         import re
  1269.         _nportprog = re.compile('^(.*):(.*)$')
  1270.     
  1271.     match = _nportprog.match(host)
  1272.     if match:
  1273.         (host, port) = match.group(1, 2)
  1274.         
  1275.         try:
  1276.             if not port:
  1277.                 raise ValueError, 'no digits'
  1278.             
  1279.             nport = int(port)
  1280.         except ValueError:
  1281.             nport = None
  1282.  
  1283.         return (host, nport)
  1284.     
  1285.     return (host, defport)
  1286.  
  1287. _queryprog = None
  1288.  
  1289. def splitquery(url):
  1290.     """splitquery('/path?query') --> '/path', 'query'."""
  1291.     global _queryprog
  1292.     if _queryprog is None:
  1293.         import re
  1294.         _queryprog = re.compile('^(.*)\\?([^?]*)$')
  1295.     
  1296.     match = _queryprog.match(url)
  1297.     if match:
  1298.         return match.group(1, 2)
  1299.     
  1300.     return (url, None)
  1301.  
  1302. _tagprog = None
  1303.  
  1304. def splittag(url):
  1305.     """splittag('/path#tag') --> '/path', 'tag'."""
  1306.     global _tagprog
  1307.     if _tagprog is None:
  1308.         import re
  1309.         _tagprog = re.compile('^(.*)#([^#]*)$')
  1310.     
  1311.     match = _tagprog.match(url)
  1312.     if match:
  1313.         return match.group(1, 2)
  1314.     
  1315.     return (url, None)
  1316.  
  1317.  
  1318. def splitattr(url):
  1319.     """splitattr('/path;attr1=value1;attr2=value2;...') ->
  1320.         '/path', ['attr1=value1', 'attr2=value2', ...]."""
  1321.     words = url.split(';')
  1322.     return (words[0], words[1:])
  1323.  
  1324. _valueprog = None
  1325.  
  1326. def splitvalue(attr):
  1327.     """splitvalue('attr=value') --> 'attr', 'value'."""
  1328.     global _valueprog
  1329.     if _valueprog is None:
  1330.         import re
  1331.         _valueprog = re.compile('^([^=]*)=(.*)$')
  1332.     
  1333.     match = _valueprog.match(attr)
  1334.     if match:
  1335.         return match.group(1, 2)
  1336.     
  1337.     return (attr, None)
  1338.  
  1339.  
  1340. def splitgophertype(selector):
  1341.     """splitgophertype('/Xselector') --> 'X', 'selector'."""
  1342.     if selector[:1] == '/' and selector[1:2]:
  1343.         return (selector[1], selector[2:])
  1344.     
  1345.     return (None, selector)
  1346.  
  1347. _hextochr = dict((lambda .0: for i in .0:
  1348. ('%02x' % i, chr(i)))(range(256)))
  1349. _hextochr.update((lambda .0: for i in .0:
  1350. ('%02X' % i, chr(i)))(range(256)))
  1351.  
  1352. def unquote(s):
  1353.     """unquote('abc%20def') -> 'abc def'."""
  1354.     res = s.split('%')
  1355.     for i in xrange(1, len(res)):
  1356.         item = res[i]
  1357.         
  1358.         try:
  1359.             res[i] = _hextochr[item[:2]] + item[2:]
  1360.         continue
  1361.         except KeyError:
  1362.             res[i] = '%' + item
  1363.             continue
  1364.             except UnicodeDecodeError:
  1365.                 res[i] = unichr(int(item[:2], 16)) + item[2:]
  1366.                 continue
  1367.             
  1368.         return ''.join(res)
  1369.  
  1370.  
  1371.  
  1372. def unquote_plus(s):
  1373.     """unquote('%7e/abc+def') -> '~/abc def'"""
  1374.     s = s.replace('+', ' ')
  1375.     return unquote(s)
  1376.  
  1377. always_safe = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.-'
  1378. _safemaps = { }
  1379.  
  1380. def quote(s, safe = '/'):
  1381.     '''quote(\'abc def\') -> \'abc%20def\'
  1382.  
  1383.     Each part of a URL, e.g. the path info, the query, etc., has a
  1384.     different set of reserved characters that must be quoted.
  1385.  
  1386.     RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
  1387.     the following reserved characters.
  1388.  
  1389.     reserved    = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
  1390.                   "$" | ","
  1391.  
  1392.     Each of these characters is reserved in some component of a URL,
  1393.     but not necessarily in all of them.
  1394.  
  1395.     By default, the quote function is intended for quoting the path
  1396.     section of a URL.  Thus, it will not encode \'/\'.  This character
  1397.     is reserved, but in typical usage the quote function is being
  1398.     called on a path where the existing slash characters are used as
  1399.     reserved characters.
  1400.     '''
  1401.     cachekey = (safe, always_safe)
  1402.     
  1403.     try:
  1404.         safe_map = _safemaps[cachekey]
  1405.     except KeyError:
  1406.         safe += always_safe
  1407.         safe_map = { }
  1408.         for i in range(256):
  1409.             c = chr(i)
  1410.             if not c in safe or c:
  1411.                 pass
  1412.             safe_map[c] = '%%%02X' % i
  1413.         
  1414.         _safemaps[cachekey] = safe_map
  1415.  
  1416.     res = map(safe_map.__getitem__, s)
  1417.     return ''.join(res)
  1418.  
  1419.  
  1420. def quote_plus(s, safe = ''):
  1421.     """Quote the query fragment of a URL; replacing ' ' with '+'"""
  1422.     if ' ' in s:
  1423.         s = quote(s, safe + ' ')
  1424.         return s.replace(' ', '+')
  1425.     
  1426.     return quote(s, safe)
  1427.  
  1428.  
  1429. def urlencode(query, doseq = 0):
  1430.     '''Encode a sequence of two-element tuples or dictionary into a URL query string.
  1431.  
  1432.     If any values in the query arg are sequences and doseq is true, each
  1433.     sequence element is converted to a separate parameter.
  1434.  
  1435.     If the query arg is a sequence of two-element tuples, the order of the
  1436.     parameters in the output will match the order of parameters in the
  1437.     input.
  1438.     '''
  1439.     if hasattr(query, 'items'):
  1440.         query = query.items()
  1441.     else:
  1442.         
  1443.         try:
  1444.             if len(query) and not isinstance(query[0], tuple):
  1445.                 raise TypeError
  1446.         except TypeError:
  1447.             (ty, va, tb) = sys.exc_info()
  1448.             raise TypeError, 'not a valid non-string sequence or mapping object', tb
  1449.  
  1450.     l = []
  1451.     if not doseq:
  1452.         for k, v in query:
  1453.             k = quote_plus(str(k))
  1454.             v = quote_plus(str(v))
  1455.             l.append(k + '=' + v)
  1456.         
  1457.     else:
  1458.         for k, v in query:
  1459.             k = quote_plus(str(k))
  1460.             if isinstance(v, str):
  1461.                 v = quote_plus(v)
  1462.                 l.append(k + '=' + v)
  1463.                 continue
  1464.             if _is_unicode(v):
  1465.                 v = quote_plus(v.encode('ASCII', 'replace'))
  1466.                 l.append(k + '=' + v)
  1467.                 continue
  1468.             
  1469.             try:
  1470.                 x = len(v)
  1471.             except TypeError:
  1472.                 v = quote_plus(str(v))
  1473.                 l.append(k + '=' + v)
  1474.                 continue
  1475.  
  1476.             for elt in v:
  1477.                 l.append(k + '=' + quote_plus(str(elt)))
  1478.             
  1479.         
  1480.     return '&'.join(l)
  1481.  
  1482.  
  1483. def getproxies_environment():
  1484.     '''Return a dictionary of scheme -> proxy server URL mappings.
  1485.  
  1486.     Scan the environment for variables named <scheme>_proxy;
  1487.     this seems to be the standard convention.  If you need a
  1488.     different way, you can pass a proxies dictionary to the
  1489.     [Fancy]URLopener constructor.
  1490.  
  1491.     '''
  1492.     proxies = { }
  1493.     for name, value in os.environ.items():
  1494.         name = name.lower()
  1495.         if value and name[-6:] == '_proxy':
  1496.             proxies[name[:-6]] = value
  1497.             continue
  1498.     
  1499.     return proxies
  1500.  
  1501. if sys.platform == 'darwin':
  1502.     
  1503.     def getproxies_internetconfig():
  1504.         '''Return a dictionary of scheme -> proxy server URL mappings.
  1505.  
  1506.         By convention the mac uses Internet Config to store
  1507.         proxies.  An HTTP proxy, for instance, is stored under
  1508.         the HttpProxy key.
  1509.  
  1510.         '''
  1511.         
  1512.         try:
  1513.             import ic
  1514.         except ImportError:
  1515.             return { }
  1516.  
  1517.         
  1518.         try:
  1519.             config = ic.IC()
  1520.         except ic.error:
  1521.             return { }
  1522.  
  1523.         proxies = { }
  1524.         if 'UseHTTPProxy' in config and config['UseHTTPProxy']:
  1525.             
  1526.             try:
  1527.                 value = config['HTTPProxyHost']
  1528.             except ic.error:
  1529.                 pass
  1530.  
  1531.             proxies['http'] = 'http://%s' % value
  1532.         
  1533.         return proxies
  1534.  
  1535.     
  1536.     def proxy_bypass(x):
  1537.         return 0
  1538.  
  1539.     
  1540.     def getproxies():
  1541.         if not getproxies_environment():
  1542.             pass
  1543.         return getproxies_internetconfig()
  1544.  
  1545. elif os.name == 'nt':
  1546.     
  1547.     def getproxies_registry():
  1548.         '''Return a dictionary of scheme -> proxy server URL mappings.
  1549.  
  1550.         Win32 uses the registry to store proxies.
  1551.  
  1552.         '''
  1553.         proxies = { }
  1554.         
  1555.         try:
  1556.             import _winreg
  1557.         except ImportError:
  1558.             return proxies
  1559.  
  1560.         
  1561.         try:
  1562.             internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings')
  1563.             proxyEnable = _winreg.QueryValueEx(internetSettings, 'ProxyEnable')[0]
  1564.             if proxyEnable:
  1565.                 proxyServer = str(_winreg.QueryValueEx(internetSettings, 'ProxyServer')[0])
  1566.                 if '=' in proxyServer:
  1567.                     for p in proxyServer.split(';'):
  1568.                         (protocol, address) = p.split('=', 1)
  1569.                         import re
  1570.                         if not re.match('^([^/:]+)://', address):
  1571.                             address = '%s://%s' % (protocol, address)
  1572.                         
  1573.                         proxies[protocol] = address
  1574.                     
  1575.                 elif proxyServer[:5] == 'http:':
  1576.                     proxies['http'] = proxyServer
  1577.                 else:
  1578.                     proxies['http'] = 'http://%s' % proxyServer
  1579.                     proxies['ftp'] = 'ftp://%s' % proxyServer
  1580.             
  1581.             internetSettings.Close()
  1582.         except (WindowsError, ValueError, TypeError):
  1583.             pass
  1584.  
  1585.         return proxies
  1586.  
  1587.     
  1588.     def getproxies():
  1589.         '''Return a dictionary of scheme -> proxy server URL mappings.
  1590.  
  1591.         Returns settings gathered from the environment, if specified,
  1592.         or the registry.
  1593.  
  1594.         '''
  1595.         if not getproxies_environment():
  1596.             pass
  1597.         return getproxies_registry()
  1598.  
  1599.     
  1600.     def proxy_bypass(host):
  1601.         
  1602.         try:
  1603.             import _winreg
  1604.             import re
  1605.         except ImportError:
  1606.             return 0
  1607.  
  1608.         
  1609.         try:
  1610.             internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings')
  1611.             proxyEnable = _winreg.QueryValueEx(internetSettings, 'ProxyEnable')[0]
  1612.             proxyOverride = str(_winreg.QueryValueEx(internetSettings, 'ProxyOverride')[0])
  1613.         except WindowsError:
  1614.             return 0
  1615.  
  1616.         if not proxyEnable or not proxyOverride:
  1617.             return 0
  1618.         
  1619.         (rawHost, port) = splitport(host)
  1620.         host = [
  1621.             rawHost]
  1622.         
  1623.         try:
  1624.             addr = socket.gethostbyname(rawHost)
  1625.             if addr != rawHost:
  1626.                 host.append(addr)
  1627.         except socket.error:
  1628.             pass
  1629.  
  1630.         
  1631.         try:
  1632.             fqdn = socket.getfqdn(rawHost)
  1633.             if fqdn != rawHost:
  1634.                 host.append(fqdn)
  1635.         except socket.error:
  1636.             pass
  1637.  
  1638.         proxyOverride = proxyOverride.split(';')
  1639.         i = 0
  1640.         while i < len(proxyOverride):
  1641.             if proxyOverride[i] == '<local>':
  1642.                 proxyOverride[i:i + 1] = [
  1643.                     'localhost',
  1644.                     '127.0.0.1',
  1645.                     socket.gethostname(),
  1646.                     socket.gethostbyname(socket.gethostname())]
  1647.             
  1648.             i += 1
  1649.         for test in proxyOverride:
  1650.             test = test.replace('.', '\\.')
  1651.             test = test.replace('*', '.*')
  1652.             test = test.replace('?', '.')
  1653.             for val in host:
  1654.                 if re.match(test, val, re.I):
  1655.                     return 1
  1656.                     continue
  1657.             
  1658.         
  1659.         return 0
  1660.  
  1661. else:
  1662.     getproxies = getproxies_environment
  1663.     
  1664.     def proxy_bypass(host):
  1665.         return 0
  1666.  
  1667.  
  1668. def test1():
  1669.     s = ''
  1670.     for i in range(256):
  1671.         s = s + chr(i)
  1672.     
  1673.     s = s * 4
  1674.     t0 = time.time()
  1675.     qs = quote(s)
  1676.     uqs = unquote(qs)
  1677.     t1 = time.time()
  1678.     if uqs != s:
  1679.         print 'Wrong!'
  1680.     
  1681.     print repr(s)
  1682.     print repr(qs)
  1683.     print repr(uqs)
  1684.     print round(t1 - t0, 3), 'sec'
  1685.  
  1686.  
  1687. def reporthook(blocknum, blocksize, totalsize):
  1688.     print 'Block number: %d, Block size: %d, Total size: %d' % (blocknum, blocksize, totalsize)
  1689.  
  1690.  
  1691. def test(args = []):
  1692.     if not args:
  1693.         args = [
  1694.             '/etc/passwd',
  1695.             'file:/etc/passwd',
  1696.             'file://localhost/etc/passwd',
  1697.             'ftp://ftp.python.org/pub/python/README',
  1698.             'http://www.python.org/index.html']
  1699.         if hasattr(URLopener, 'open_https'):
  1700.             args.append('https://synergy.as.cmu.edu/~geek/')
  1701.         
  1702.     
  1703.     
  1704.     try:
  1705.         for url in args:
  1706.             print '----------', url, '----------'
  1707.             (fn, h) = urlretrieve(url, None, reporthook)
  1708.             print fn
  1709.             if h:
  1710.                 print '======'
  1711.                 for k in h.keys():
  1712.                     print k + ':', h[k]
  1713.                 
  1714.                 print '======'
  1715.             
  1716.             fp = open(fn, 'rb')
  1717.             data = fp.read()
  1718.             del fp
  1719.             if '\r' in data:
  1720.                 table = string.maketrans('', '')
  1721.                 data = data.translate(table, '\r')
  1722.             
  1723.             print data
  1724.             (fn, h) = (None, None)
  1725.         
  1726.         print '-' * 40
  1727.     finally:
  1728.         urlcleanup()
  1729.  
  1730.  
  1731.  
  1732. def main():
  1733.     import getopt
  1734.     import sys
  1735.     
  1736.     try:
  1737.         (opts, args) = getopt.getopt(sys.argv[1:], 'th')
  1738.     except getopt.error:
  1739.         msg = None
  1740.         print msg
  1741.         print 'Use -h for help'
  1742.         return None
  1743.  
  1744.     t = 0
  1745.     for o, a in opts:
  1746.         if o == '-t':
  1747.             t = t + 1
  1748.         
  1749.         if o == '-h':
  1750.             print 'Usage: python urllib.py [-t] [url ...]'
  1751.             print '-t runs self-test;', 'otherwise, contents of urls are printed'
  1752.             return None
  1753.             continue
  1754.     
  1755.     if t:
  1756.         if t > 1:
  1757.             test1()
  1758.         
  1759.         test(args)
  1760.     elif not args:
  1761.         print 'Use -h for help'
  1762.     
  1763.     for url in args:
  1764.         print urlopen(url).read(),
  1765.     
  1766.  
  1767. if __name__ == '__main__':
  1768.     main()
  1769.  
  1770.